
import { useRef, useState } from "react";
import { _upload } from "../../api"


let My: React.FC = () => {
    const file = useRef<HTMLInputElement>(null);
    const [src ,setSrc ] = useState<string>("");

    const upload = async () => {
        const files = (file.current?.files as FileList)[0];
        const MiMeType = ["image/png", "image/jpg", "image/jpeg", "image/gif"];
        if (files) {
            //  获取上传文件的后缀和大小
            if (MiMeType.includes(files.type)) {
                if (files.size / 1024 / 1024 >= 10) {
                    alert("图片过大，图片大小不能超过10MB")
                } else {
                    let formData = new FormData();
                    formData.append("file", files);
                    const { data } = await _upload(formData);
                    alert(data.msg);
                    if(data.code){
                        setSrc(data.url)
                    }
                }
            } else {
                alert("图片格式只能是png jpg jpeg gif中的一种")
            }

        } else {
            alert("请先选择图片")
        }

    };
    return (
        <div>
            <input type="file" ref={file} />
            <button onClick={() => upload()}>开始上传</button>
            <img src={src} alt="" />
        </div>
    )
};


export default My;